﻿var lsInfo = {
  current: 1,
  pageSize: allPageSize,
  data: [],
  totalRow: 0,
  totalPage: 0,
  oneDate: {},
  editState: false
};


// var projectid = getUrlId();

var add = true;
var projectId = getUrlId().id;
var start = getUrlId().start.split('#').join(' ');
var end = getUrlId().end.split('#').join(' ');
function getUrlId() {
  var url = window.location.href;
  url = url.slice(url.lastIndexOf('/') + 1).split('#-#');
  return {
    id: url[0],
    start: url[1],
    end: url[2]
  }
}

// document.getElementById('nav').innerHTML = template('navs', navinfo3);

$('#nav li').eq(0).addClass('active');

allCost();
function allCost() {
  $.ajax({
    cache: false,
    async: false,
    url: '/api/CommonApi?API=GetProjectCountMoney',
    type: 'get',
    data: {
      ProjectID: projectId
    },
    dataType: 'json',
    success: function (data) {
      // console.log(data)
      if (data.Success) {
        console.log(data);
        var cost = data.ApiParamObj[0].CountMoney;
        $('#allCost').html(cost);
      }
    }
  });
}


var getList = function (obj) {
  $.ajax({
    cache: false,
    async: false,
    url: '/api/CommonApi?API=GetProjectCostDetail',
    type: 'get',
    data: {
      ProjectID: projectId,
      sorts: ' CostDate DESC',
      pagesize: obj.size,
      page: obj.index
    },
    dataType: 'json',
    success: function (data) {
      // console.log(data)
      if (data.Success) {
        obj.callback(data)
      }
    }
  });
};

getList({
  size: lsInfo.pageSize,
  index: lsInfo.current,
  callback: function (data) {
    // console.log(data)
    // console.log(JSON.stringify(data));
    var newData = data.ApiParamObj[0];
    for (var key in newData) {
      if (newData[key]['State'] === '????') {
        newData[key]['State'] = '';
      }
    }
    // 列表数据
    document.getElementById('listTable').innerHTML = template('l3List', newData);
    // 分页
    var pagesInfo = data.ApiParamObj[1];
    lsInfo.data = newData;
    lsInfo.totalRow = pagesInfo[0].totalRow;
    lsInfo.totalPage = pagesInfo[0].totalPage;

    $('#totalRow').html(lsInfo.totalRow);
    pagesSet(lsInfo);
    setPageSize(lsInfo);
    loading.hide();
  }
});

// 点击分页请求事件
var showPage = function (o) {
  // console.log(o)
  getList({
    size: o.pageSize,
    index: o.current,
    callback: function (data) {
      // console.log(data)
      // // console.log(JSON.stringify(data));
      // if(newData.length === 0) {
      //   o.current = o.current - 1;
      //   showPage(o);
      //   return;
      // }
      var newData = data.ApiParamObj[0];
      for (var key in newData) {
        if (newData[key]['State'] === '????') {
          newData[key]['State'] = '';
        }
      }
      // 列表数据
      document.getElementById('listTable').innerHTML = template('l3List', newData);
      // 分页
      var pagesInfo = data.ApiParamObj[1];
      o.data = newData;
      o.totalRow = pagesInfo[0].totalRow;
      o.totalPage = pagesInfo[0].totalPage;

      $('#totalRow').html(o.totalRow);
      pagesSet(o);
      loading.hide();
    }
  });
};

GetDictionarys('PROJECT_EXP', function (data) {
  // console.log(data)
  var arr = {};
  // console.log(JSON.stringify(data));
  var obj = {};
  var list = data.ApiParamObj;
  var i = 0;
  var l = list.length;

  for (; i < l; i++) {
    if (!obj[list[i].Key]) {
      obj[list[i].Key] = [];
      arr[list[i].Key] = list[i].Logogram;
    }
    obj[list[i].Key].push(list[i]);
  }
  // console.log(obj)
  load(obj, arr);
});

function load(obj, arr) {
  // console.log(obj)
  var b = new Vue({
    el: '#form',
    data: {
      form: {
        cName: '',
        cost: '',
        date: '',
        etc: ''
      },
      select: obj['PROJECT_EXP'],
      allList: []
    },
    methods: {
      del: function ($index) {
        b.allList.splice($index, 1);
      },
      add: function () {
        var v = b.form;

        var validator = new Validator();
        validator.add(v.cName, [{
          strategy: 'isNonEmpty',
          errorMsg: '费用名称不能为空'
        }]);

        validator.add(v.cost, [{
          strategy: 'isNonEmpty',
          errorMsg: '费用金额不能为空'
        }]);

        validator.add(parseInt(v.cost, 10), [{
          strategy: 'isRMB',
          errorMsg: '费用金额必须为数字'
        }]);

        validator.add(v.date, [{
          strategy: 'isNonEmpty',
          errorMsg: '使用日期不能为空'
        }]);

        // console.log(parseInt(v.cost, 10));
        var errmsg = validator.start();
        if (errmsg) {
          alert(errmsg);
          return false;
        }

        var name = '';
        var i = 0;
        var o = b.select;
        var l = o.length;
        for (;i < l;i++) {
          if (v.cName === o[i].ID) {
            name = o[i].Text;
          }
        }
        var submitObj = {
          ProjectID: projectId,
          CostTypeID: v.cName,
          CostDate: v.date,
          Money: v.cost,
          Remark: v.etc
        };
        $.ajax({
          url: '/api/CommonApi?API=CostDetailTableOp',
          type: 'put',
          data: {
            ApiParamObj: JSON.stringify(submitObj)
          },
          dataType: 'json',
          success: function (data) {
            if (data.Success) {
              console.log('Add success');
              showPage(lsInfo);
              // datetimepicker();
              b.allList.push({
                name: name,
                cost: v.cost,
                date: v.date,
                etc: v.etc
              });

              resetForm();

              setTimeout(function () {
                datetimepicker();
              }, 0);
            }
          }
        });
        // console.log(b1.allList)
        /*b.allList.push({
         cName: '',
         cost: '',
         date: '',
         etc: ''
         });*/


      }
    }
  });

  function datetimepicker() {
    /*$('#form .date').datepicker({
      // bootcssVer: 3,
      todayBtn: 'linked',
      weekStart: 0,
      autoclose: true,
      // todayHighlight: 1,
      startView: 0,
      startDate: new Date().pattern('yyyy-MM-dd'),
      format: 'yyyy-mm-dd',
      // forceParse: 1,
      // showMeridian: 1,
      language: 'zh-CN',
      minView: 0
    });*/
    $('.input-daterange input').datetimepicker({
      bootcssVer: 2,
      todayBtn: true,
      weekStart: 0,
      autoclose: 1,
      startView: 2,
      startDate: new Date().pattern('yyyy-MM-dd'),
      format: 'yyyy-mm-dd',
      language: 'zh-CN',
      minView: 2
    });
  }

  datetimepicker();

  $('.c-select-btn.remove.glyphicon-remove').on('click', function () {
    $(this).prev().val('');
    return false;
  });

  $('#add').click(function () {
    resetForm();
    $('#costPost').modal('show');
  });


  $('#listTable').on('click', '.del', function () {
    var _this = $(this);
    var index = _this.parent().parent().index();
    lsInfo.oneDate = lsInfo.data[index];
    var v = lsInfo.oneDate;
    // console.log(JSON.stringify(v))
    // console.log(v.ID)
    $.ajax({
      url: '/api/CommonApi?API=CostDetailTableOp',
      type: 'post',
      data: {
        ApiParamObj: JSON.stringify({
          ID: v.ID,
          IsDelete: 1
        })
      },
      dataType: 'json',
      success: function (data) {
        // console.log(data)
        if (data.Success) {
          console.log('del success');

          b.allList = [];
          showPage(lsInfo);
        }
      }
    });
  });

  function resetForm() {
    b.form = {
      cName: '',
      cost: '',
      date: '',
      etc: ''
    };
  }
}